package com.example.edianzu.somur;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.AppCompatRadioButton;
import android.view.KeyEvent;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.edianzu.somur.api.bean.LoginInfo;
import com.example.edianzu.somur.module.adapter.MainFragmentPagerAdapter;
import com.example.edianzu.somur.module.appointment.AppointmentFragment;
import com.example.edianzu.somur.module.exercise.ExerciseFragment;
import com.example.edianzu.somur.module.health.HealthFragment;
import com.example.edianzu.somur.module.mine.MineFragment;
import com.example.edianzu.somur.utils.content.L;
import com.example.edianzu.somur.utils.content.StatusBarUtils;
import com.example.edianzu.somur.utils.view.BaseActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.badgeview.BGABadgeRadioButton;
import cn.bingoogolapple.badgeview.BGABadgeViewHelper;

public class MainActivity extends BaseActivity implements ViewPager.OnPageChangeListener, RadioGroup.OnCheckedChangeListener {

    @BindView(R.id.mainActivity_radioGroup)
    RadioGroup mainActivity_radioGroup;
    @BindView(R.id.mainActivity_ViewPager)
    ViewPager mainActivityViewPager;
    @BindView(R.id.activity_RadioButton_health)
    BGABadgeRadioButton activityRadioButtonHealth;
    @BindView(R.id.activity_RadioButton_appointment)
    AppCompatRadioButton activityRadioButtonAppointment;
    @BindView(R.id.activity_RadioButton_exercise)
    AppCompatRadioButton activityRadioButtonExercise;
    @BindView(R.id.activity_RadioButton_mine)
    AppCompatRadioButton activityRadioButtonMine;
    private int member_id;
    private LoginInfo loginInfo;
    private MainFragmentPagerAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtils.setWindowStatusBarColor(this, R.color.title);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

//        初始化BadgeView
        initBadgeView();

        changeImageSize();

//        mainActivityViewPager.setOffscreenPageLimit(2);

        initFragment();

        //        默认选中第一个
        ((RadioButton) mainActivity_radioGroup.getChildAt(0)).setChecked(true);
//        mainActivityViewPager.setCurrentItem(0);

        mainActivityViewPager.setOnPageChangeListener(this);
        mainActivity_radioGroup.setOnCheckedChangeListener(this);

//        HealthFragment healthFragment=new HealthFragment();
//        Bundle bundle=new Bundle();
        member_id = getIntent().getIntExtra("member_id", 10);
//        bundle.putInt("member_id", member_id);

        loginInfo = (LoginInfo) getIntent().getSerializableExtra("login");

        L.d("onCreate", "onCreate: " + member_id);

        L.d("onCreate", "onCreate: " + loginInfo.getData().getPassword());
//        healthFragment.setArguments(bundle);
    }

    private void initBadgeView() {

//        mainActivity_radioGroup.setPadding(0,0,120,0);

        activityRadioButtonHealth.setPadding(120,0,0,120);
        activityRadioButtonHealth.showCirclePointBadge();
        //初始化
//        activityRadioButtonHealth.showTextBadge("9");
//        activityRadioButtonHealth.getBadgeViewHelper().setBadgeTextSizeSp(15);
        activityRadioButtonHealth.getBadgeViewHelper().setBadgeTextColorInt(Color.WHITE);
        activityRadioButtonHealth.getBadgeViewHelper().setBadgeBgColorInt(Color.RED);
        activityRadioButtonHealth.getBadgeViewHelper().setDragable(true);
//        activityRadioButtonHealth.getBadgeViewHelper().setBadgePaddingDp(6);
//        activityRadioButtonHealth.getBadgeViewHelper().setBadgeVerticalMarginDp(2);
//        activityRadioButtonHealth.getBadgeViewHelper().setBadgeHorizontalMarginDp(2);
        activityRadioButtonHealth.getBadgeViewHelper().setBadgeGravity(BGABadgeViewHelper.BadgeGravity.RightTop);
//        activityRadioButtonHealth.getBadgeViewHelper().setBadgeBorderWidthDp(2);
    }

    //宿主activity中的getTitles()方法
    public int getMember_id() {
        return member_id;
    }

    public LoginInfo getLoginInfo() {
        return loginInfo;
    }

    private void initFragment() {

        List<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(new HealthFragment());
        fragmentList.add(new AppointmentFragment());
        fragmentList.add(new ExerciseFragment());
        fragmentList.add(new MineFragment());

        adapter = new MainFragmentPagerAdapter(getSupportFragmentManager(), fragmentList);
        mainActivityViewPager.setAdapter(adapter);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

        ((RadioButton) mainActivity_radioGroup.getChildAt(position)).setChecked(true);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {

        switch (checkedId) {

            case R.id.activity_RadioButton_health:
                mainActivityViewPager.setCurrentItem(0);
                break;
            case R.id.activity_RadioButton_appointment:
                mainActivityViewPager.setCurrentItem(1);
                break;
            case R.id.activity_RadioButton_exercise:
                mainActivityViewPager.setCurrentItem(2);
                break;
            case R.id.activity_RadioButton_mine:
                mainActivityViewPager.setCurrentItem(3);
                break;
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {

//        FragmentManager fragmentManager=getSupportFragmentManager();

        if(event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0){
            if(adapter.getCurrentFragment() instanceof AppointmentFragment){
                ((AppointmentFragment) adapter.getCurrentFragment()).dispatchKeyEvent(event);
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    //记录用户首次点击返回键的时间
    private long firstTime = 0;
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {

            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = secondTime;
                return true;
            } else {
                System.exit(0);
//                ActivityManager.finishAll();
            }
        }
        return super.onKeyUp(keyCode, event);
    }

    //   定义底部标签图片大小
    private void changeImageSize() {

        Drawable drawableFirst = getResources().getDrawable(R.drawable.radiobutton_health);
        drawableFirst.setBounds(0, 0, 156, 156);//第一0是距左右边距离，第二0是距上下边距离，第三69长度,第四宽度
        activityRadioButtonHealth.setCompoundDrawables(null, drawableFirst, null, null);//只放上面

        Drawable drawableSearch = getResources().getDrawable(R.drawable.radiobutton_appointment);
        drawableSearch.setBounds(0, 0, 156, 156);//第一0是距左右边距离，第二0是距上下边距离，第三69长度,第四宽度
        activityRadioButtonAppointment.setCompoundDrawables(null, drawableSearch, null, null);//只放上面

        Drawable drawableExercise = getResources().getDrawable(R.drawable.radiobutton_exercise);
        drawableExercise.setBounds(0, 0, 156, 156);//第一0是距左右边距离，第二0是距上下边距离，第三69长度,第四宽度
        activityRadioButtonExercise.setCompoundDrawables(null, drawableExercise, null, null);//只放上面

        Drawable drawableMine = getResources().getDrawable(R.drawable.radiobutton_mine);
        drawableMine.setBounds(0, 0, 156, 156);//第一0是距左右边距离，第二0是距上下边距离，第三69长度,第四宽度
        activityRadioButtonMine.setCompoundDrawables(null, drawableMine, null, null);//只放上面ffffffff}
    }

//    public void RequestPermission(){
//
//        //当api版本大于22进行权限检查
//        if (Build.VERSION.SDK_INT>22){
//            //检车权限
//            int cameraState = checkSelfPermission(Manifest.permission.CAMERA);
//            int contactsState = checkSelfPermission(Manifest.permission.READ_CONTACTS);
//
//            if (cameraState != PackageManager.PERMISSION_GRANTED && contactsState != PackageManager.PERMISSION_GRANTED){
//                //没有赋予权限 申请权限
//                //申请权限
//                /**
//                 * 参数1： String []  要申请的权限
//                 * 参数2： requestCode
//                 */
//                requestPermissions(new String []{Manifest.permission.CAMERA,Manifest.permission.READ_CONTACTS},100);
//
//            }else {
//                //已经赋予权限  无需处理
//
//            }
//
//        }
//    }
//
//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        //请求回调方法
//        if (requestCode ==100) {
//            for (String permission : permissions) {
//                Log.e("tag", "onRequestPermissionsResult: 请求的权限：" + permission );
//            }
//
//            for (int grantResult : grantResults) {
//                if (grantResult == 0) {
//                    //获取成功
//                    Log.e("", "onRequestPermissionsResult: ");
//                }else {
//                    //用户没有赋予权限
//                    //再次申请  慎用
//                    //给用户提示 弹出Dialog 表名情况 再次申请，否者退出程序！
//                }
//            }
//        }
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//    }
}
